package cn.chenli.job.config;

import cn.chenli.job.annotation.Mapping;
import cn.chenli.job.common.config.Routes;
import cn.chenli.job.common.controller.Action;
import cn.chenli.job.controller.BaseController;
import org.asyou.mongo.base.MongoConfig;
import org.asyou.mongo.base.MongoManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pro.tools.system.ToolClassSearch;

import java.lang.reflect.Method;
import java.util.Set;

/**
 * @author chenli
 * @create 2017-08-11
 */
public class Config {

    private static final Logger log = LoggerFactory.getLogger(Config.class);

    public void configureDB() {
        MongoConfig mongoConfig = new MongoConfig("test", "127.0.0.1", 27017, "test_servlet");
        try {
            if (MongoManager.putMongoConfig(mongoConfig)) {
                log.info("mongodb数据源加载成功");
            } else
                log.info("mongodb数据源加载失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 注入路由执行
     */
    public void setController() {
        GlobalConfig.controllerList.forEach(clazz -> {
            Mapping mapping = clazz.getAnnotation(Mapping.class);
            if (mapping == null) {
                throw new RuntimeException("注入映射失败，失败原因,没有添加Mapping注解，该controller:" + clazz.getName());
            }
            String[] values = mapping.value();
            Method[] methods = clazz.getDeclaredMethods();//反射其方法注入路由
            for (String value : values) {
                if (!"/".equals(value.substring(value.length() - 1))) {
                    value = value + "/";
                }
                for (Method method : methods) {
                    String url = value + method.getName();
                    Action action = new Action(url, method.getName(),mapping.viewPath(), clazz);
                    if(GlobalConfig.controllerMap.put(url, action) != null){
                        String sb = "注解路由重复：" +
                                clazz.getName() + "." +
                                method.getName() + ", \"" +
                                url +
                                " \"" + "is already in use.";
                        throw new RuntimeException(sb);
                    }
                }
            }
        });

    }

    @SuppressWarnings("unchecked")
    public void addControllerClass(Routes routes) {
        Set<Class<?>> controllerClasses = ToolClassSearch.getClazz(BaseController.class);
        controllerClasses.remove(BaseController.class);
        // 循环处理自动注册映射
        for (Class controller : controllerClasses) {
            //反射出所有的方法，将其放入
            routes.add(controller);
        }
    }
}